package com.dex4d.core.subscribers;

import android.content.Context;
import android.widget.Toast;

import com.dex4d.core.AppBaseActivity;
import com.dex4d.core.progress.ProgressCancelListener;
import com.dex4d.utils.Log;
import com.dex4d.core.http.ApiException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import rx.Subscriber;

public abstract class ProgressSubscriber<T> extends Subscriber<T> implements ProgressCancelListener {
    private static String TAG = "ProgressSubscriber";

//    private LoadingDialog mLoadingDialog;

    private Context context;

    private boolean showDialog = true;

    public ProgressSubscriber(Context context) {
        this.context = context;
    }

    public ProgressSubscriber(Context context, boolean show) {
        this.context = context;
        this.showDialog = show;
    }

    private void showProgressDialog(){
        if(showDialog){
            ((AppBaseActivity)context).showLoadingDialog();
        }
    }

    private void dismissProgressDialog(){
        if(showDialog){
            ((AppBaseActivity)context).dismissLoadingDialog();
        }
    }

    /**
     * 订阅开始时调用
     * 显示ProgressDialog
     */
    @Override
    public void onStart() {
        showProgressDialog();
    }

    /**
     * 完成，隐藏ProgressDialog
     */
    @Override
    public void onCompleted() {
        dismissProgressDialog();
    }

    /**
     * 对错误进行统一处理
     * 隐藏ProgressDialog
     * @param e
     */
    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
        if (e instanceof SocketTimeoutException) {
            Toast.makeText(context, "网络中断，请检查您的网络状态", Toast.LENGTH_SHORT).show();
            Log.e(TAG,"SocketTimeoutException:"+e.getMessage());
        } else if (e instanceof ConnectException) {
            Toast.makeText(context, "网络中断，请检查您的网络状态", Toast.LENGTH_SHORT).show();
            Log.e(TAG,"ConnectException:"+e.getMessage());
        } else if(e instanceof ApiException){
            ApiException error = (ApiException)e;
            Toast.makeText(context, "ApiException error:" + error.getErrorCode() + error.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e(TAG,"ApiException error code:"+error.getErrorCode() + " error message:"+error.getMessage());
        }else {
            Toast.makeText(context, "unknown error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e(TAG,"unknown error:"+e.getMessage());
        }
    }

    /**
     * 取消ProgressDialog的时候，取消对observable的订阅，同时也取消了http请求
     */
    @Override
    public void onCancelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }
}